<template>
  <div class="bridge-rule-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left">
        <h2 class="page-title">评分规则管理</h2>
      </div>
      <div class="right">
        <el-button 
          type="default" 
          icon="RefreshRight" 
          circle 
          @click="getList" 
          title="刷新列表" 
          class="refresh-button"
        ></el-button>
        <el-button type="primary" @click="handleAdd" class="custom-button">
          <el-icon><Plus /></el-icon> 新增规则
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      class="custom-table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="eventType" label="适用事件类型" width="150">
        <template #default="{ row }">
          {{ getDictLabel("warn_type", row.eventType) }}
        </template>
      </el-table-column>
      <el-table-column prop="content" label="评估维度" min-width="200" show-overflow-tooltip />
      <el-table-column prop="maxScore" label="最高分值" width="100" align="center">
        <template #default="{ row }">
          {{ row.maxScore }}分
        </template>
      </el-table-column>
      <el-table-column prop="weight" label="权重" width="100" align="center">
        <template #default="{ row }">
          {{ (row.weight * 100).toFixed(0) }}%
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'" class="status-tag">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)" class="operation-button">
            编辑
          </el-button>
          <el-button link @click="handleDelete(row)" class="operation-button danger">
            删除
          </el-button>
          <el-button 
            link 
            :type="row.status === 1 ? 'warning' : 'success'" 
            @click="handleToggleStatus(row)" 
            class="operation-button"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      class="custom-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="dialog-form"
      >
        <el-form-item label="适用事件类型" prop="eventType">
          <el-select v-model="form.eventType" placeholder="请选择适用事件类型" class="w-full">
            <el-option
              v-for="item in typeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评估维度" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            :rows="3"
            placeholder="请输入该评估维度的内容描述"
          />
        </el-form-item>
        <el-form-item label="最高分值" prop="maxScore">
          <el-input-number
            v-model="form.maxScore"
            :min="1"
            :max="100"
            :precision="0"
            controls-position="right"
            class="w-half"
          />
          <span class="unit-text">分</span>
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-slider
            v-model="sliderValue"
            :min="1"
            :max="100"
            :format-tooltip="formatTooltip"
            @change="handleSliderChange"
          />
          <div class="weight-display">
            {{ (form.weight * 100).toFixed(0) }}%
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getEvaluationRuleList,
  getEvaluationRuleDetail,
  addEvaluationRule,
  updateEvaluationRule,
  deleteEvaluationRule
} from "@/api/bridge/command/evaluation";
import { listData } from "@/api/system/dict/data";
import { Plus, RefreshRight } from '@element-plus/icons-vue';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);

// 字典数据
const typeOptions = ref([]);
const dictMap = ref({});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form = ref({
  id: "",
  eventType: undefined,
  content: "",
  maxScore: 10,
  weight: 0.25,
  status: 1
});

// 滑块值
const sliderValue = ref(25);

// 格式化滑块提示
const formatTooltip = (value) => {
  return value + '%';
};

// 处理滑块变化
const handleSliderChange = (value) => {
  form.value.weight = value / 100;
};

// 表单校验规则
const rules = {
  eventType: [{ required: true, message: "请选择适用事件类型", trigger: "change" }],
  content: [{ required: true, message: "请输入评估维度", trigger: "blur" }],
  maxScore: [{ required: true, message: "请输入最高分值", trigger: "change" }],
  weight: [{ required: true, message: "请设置权重", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
};

// 获取字典数据
const getDictData = async () => {
  try {
    const res = await listData({
      dictType: "warn_type",
      pageNum: 1,
      pageSize: 100,
      dictName: "",
      dictLabel: ""
    });
    if (res.code === 200) {
      typeOptions.value = res.rows;
      
      // 构建字典映射
      dictMap.value = {};
      dictMap.value['warn_type'] = {};
      res.rows.forEach(item => {
        dictMap.value['warn_type'][item.dictValue] = item.dictLabel;
      });
    }
  } catch (error) {
    console.error("获取字典数据失败:", error);
  }
};

// 获取字典标签
const getDictLabel = (dictType, value) => {
  if (!value || !dictMap.value[dictType]) return '-';
  return dictMap.value[dictType][value] || value;
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };
    const res = await getEvaluationRuleList(params);
    if (res.code === 200) {
      tableData.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = "新增评分规则";
  form.value = {
    id: "",
    eventType: undefined,
    content: "",
    maxScore: 10,
    weight: 0.25,
    status: 1
  };
  sliderValue.value = 25; // 重置滑块值
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  try {
    const res = await getEvaluationRuleDetail(row.id);
    if (res.code === 200) {
      form.value = {
        ...res.data
      };
      
      // 设置滑块值
      sliderValue.value = form.value.weight * 100;
      
      dialogTitle.value = "编辑评分规则";
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该评分规则吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      const res = await deleteEvaluationRule(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 处理状态切换
const handleToggleStatus = (row) => {
  const statusText = row.status === 1 ? '禁用' : '启用';
  ElMessageBox.confirm(`确认${statusText}该评分规则吗？`, "提示", {
    type: "warning",
  }).then(async () => {
    try {
      const updatedData = {
        ...row,
        status: row.status === 1 ? 0 : 1
      };
      const res = await updateEvaluationRule(updatedData);
      if (res.code === 200) {
        ElMessage.success(`${statusText}成功`);
        getList();
      } else {
        ElMessage.error(res.msg || `${statusText}失败`);
      }
    } catch (error) {
      ElMessage.error(`${statusText}失败`);
    }
  });
};

// 表格选择改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = { ...form.value };
        
        if (form.value.id) {
          const res = await updateEvaluationRule(submitData);
          if (res.code === 200) {
            ElMessage.success("修改成功");
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg || "修改失败");
          }
        } else {
          const res = await addEvaluationRule(submitData);
          if (res.code === 200) {
            ElMessage.success("新增成功");
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg || "新增失败");
          }
        }
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

onMounted(() => {
  getList();
  getDictData();
});
</script>

<style scoped lang="scss">
.bridge-rule-container {
  padding: 20px;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);

  .operation-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    background: var(--el-bg-color-overlay);
    padding: 16px;
    border-radius: 4px;

    .left {
      .page-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .right {
      display: flex;
      gap: 12px;
    }

    .custom-button {
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }

    .refresh-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: rotate(180deg);
      }
    }
  }

  .custom-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    background: var(--el-bg-color-overlay);

    :deep(th) {
      background: var(--el-bg-color-page) !important;
    }

    :deep(.el-table__row) {
      background-color: var(--el-bg-color-overlay);
    }

    .operation-button {
      padding: 2px 8px;
      margin: 0 2px;
      font-size: 12px;

      &.danger {
        color: var(--el-color-danger);
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    background: var(--el-bg-color-overlay);

    .el-dialog__header {
      background: var(--el-bg-color-page);
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-light);
      padding: 15px 20px;
    }
  }

  .dialog-form {
    :deep(.el-form-item__label) {
      color: var(--el-text-color-regular);
    }

    :deep(.el-input__inner) {
      background-color: var(--el-bg-color-overlay);
      border-color: var(--el-border-color);
      color: var(--el-text-color-primary);
    }
  }
}

.w-full {
  width: 100%;
}

.w-half {
  width: 50%;
}

.unit-text {
  margin-left: 10px;
  color: var(--el-text-color-regular);
}

.weight-display {
  margin-top: 8px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-color-primary);
}

/* 状态标签样式 */
.status-tag {
  font-weight: bold;
  padding: 0 10px;
  border-radius: 4px;
}
</style> 